package com.tanhua.dubbo.server.api;

import com.alibaba.dubbo.config.annotation.Service;
import com.tanhua.dubbo.server.pojo.RecommendUser;
import com.tanhua.dubbo.server.pojo.Visitors;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;
import java.util.Queue;

/**
 * @Author: cloudy
 * @Description:
 * @Date: Created in 18:51 2021/1/13
 * @ModifiedBy:
 */
@Service(version = "1.0.0")
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public String saveVisitor(Visitors visitors) {
        visitors.setId(ObjectId.get());
        visitors.setDate(System.currentTimeMillis());
        this.mongoTemplate.save(visitors);
        return visitors.getId().toHexString();
    }

    @Override
    public List<Visitors> topVisitor(Long userId, Integer num) {
        Query query = Query.query(Criteria.where("userId").is(userId)).with(Sort.by(Sort.Order.desc("date"))).limit(num);
        return getVisitorsList(query);
    }

    @Override
    public List<Visitors> topVisitor(Long userId, Long date) {
        Query query = Query.query(Criteria.where("userId").is(userId).and("date").lt(date)).with(Sort.by(Sort.Order.desc("date")));
        return this.getVisitorsList(query);
    }

    private List<Visitors> getVisitorsList(Query query) {
        List<Visitors> visitorsList = this.mongoTemplate.find(query, Visitors.class);

        //上面查询到的是访问我的访客,里面的缘分值并未填充,因此需要通过recommendUser来填充数据
        for (Visitors visitors : visitorsList) {
            RecommendUser recommendUser = this.mongoTemplate.findOne(Query.query(Criteria.where("toUserId").is(visitors.getUserId()).and("userId").is(visitors.getVisitorUserId())), RecommendUser.class);
            if (recommendUser != null) {
                visitors.setScore(recommendUser.getScore());
            } else {
                visitors.setScore(30d);
            }
        }
        return visitorsList;
    }
}
